<?php


namespace app\admin\controller;


use app\model\AdminCategory;
use app\util\ReturnCode;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

class Category extends Base
{
    /**
     * 根据id获取数据
     * @return array
     */
    public function get()
    {
        $id = request()->param('id');
        try {
            $model = new AdminCategory();
            $where = ['id' => $id];
            $where = $this->addTid($where);
            $model->where($where);
            $data = $model->find();
            return $this->buildSuccess($data);
        } catch (Exception $e) {
        }
        return $this->buildFailed(ReturnCode::INVALID, '获取数据失败');
    }
    public function save()
    {
        $postData = $this->request->post();
        $postData = $this->addTid($postData);
        $this->addTid($postData);
        if(isset($postData['id'])){
            $result = AdminCategory::update($postData);
        }else{
            $result = AdminCategory::create($postData);
        }
        if ($result) {
            return $this->buildSuccess(null, '操作成功');
        } else {
            return $this->buildFailed(ReturnCode::FAILED, '操作失败');
        }
    }
    /**
     * 删除
     * @return array
     */
    public function del()
    {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $where = [];
        $where = $this->addTid($where);
        $where['id'] = $id;

        $done = AdminCategory::destroy($where);
        if($done){
            return $this->buildSuccess([]);
        }
        return $this->buildFailed(ReturnCode::DELETE_FAILED, '删除失败');
    }
    /**
     * 获取列表
     * @return array
     * @author chniccs
     */
    public function getList()
    {
        $obj = new AdminCategory();
        $where = [];
        $where = $this->addTid($where);
        try {
            $result = $obj->where($where)->field('id,icon,title')->select();
            return $this->buildSuccess($result);
        } catch (DataNotFoundException $e) {
        } catch (ModelNotFoundException $e) {
        } catch (DbException $e) {
        }
        return $this->buildFailed(ReturnCode::INVALID,'暂无分类');
    }
}